package com.hrrt.home.socket.utils;

import com.hrrt.home.socket.SocketTask;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 车锁socket处理
 * Created by GaoXiang
 */
public class SocketUtil {

    public static Map<String,SocketTask> socketTaskMap = Collections.synchronizedMap(new HashMap<String, SocketTask>());
    //创建线程池
    private static ExecutorService threadPool = Executors.newCachedThreadPool();
    //Socket监听服务
    private static ServerSocket server;
    //Socket监听端口
    private static Integer port = 5209;

/*
    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        try {
            start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/

/*    public static void main(String[] args) {
        try {
            start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/

    public static void start() throws IOException {
        //定义一个ServerSocket监听在指定端口上
        server = new ServerSocket(port);
        System.out.println("网关管理服务启动成功！");
        beginAccept();
    }

    /**
     * 阻塞连接，开始监控
     *
     * @throws IOException 异常
     */
    private static void beginAccept() throws IOException {
        while (true) {
            //server尝试接收其他Socket的连接请求，server的accept方法是阻塞式的。
            System.out.println("连接");
            Socket socket = server.accept();
            //每接收到一个Socket就建立一个新的线程来处理它。并添加到线程池中。
            SocketTask socketTask = new SocketTask(socket);
            threadPool.execute(new Thread(socketTask));
        }
    }
}
